package middleware

import (
	"strings"

	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web/context"
)

// LogMiddleware 操作日志中间件
func LogMiddleware(ctx *context.Context) {
	// 跳过登录接口的日志记录
	if ctx.Request.URL.Path == "/api/auth/login" {
		return
	}

	// 获取请求信息
	method := ctx.Request.Method
	path := ctx.Request.URL.Path
	ip := ctx.Input.IP()

	// 获取用户信息
	userId, ok := ctx.Input.GetData("user_id").(int64)
	username, _ := ctx.Input.GetData("username").(string)

	// 只有登录用户的操作才记录日志
	if ok && userId > 0 {
		// 解析操作类型
		operationType := parseOperationType(path, method)

		// 生成操作描述
		description := generateDescription(path, method)

		// 创建日志记录
		log := &models.OperationLog{
			UserId:        userId,
			Username:      username,
			Method:        method,
			Path:          path,
			Ip:            ip,
			OperationType: operationType,
			Description:   description,
		}

		models.AddOperationLog(log)
	}

}

// parseOperationType 解析操作类型
func parseOperationType(path string, method string) string {
	// 移除前缀
	path = strings.TrimPrefix(path, "/api/")

	// 分割路径
	parts := strings.Split(path, "/")
	if len(parts) < 2 {
		return "其他"
	}

	// 获取主要模块
	module := parts[0]

	// 根据HTTP方法和模块确定操作类型
	switch method {
	case "GET":
		return module + ":查询"
	case "POST":
		return module + ":创建"
	case "PUT":
		return module + ":更新"
	case "DELETE":
		return module + ":删除"
	default:
		return module + ":其他"
	}
}

// generateDescription 生成操作描述
func generateDescription(path string, method string) string {
	path = strings.TrimPrefix(path, "/api/")
	parts := strings.Split(path, "/")
	if len(parts) < 2 {
		return "未知操作"
	}

	module := parts[0]
	operation := ""
	if len(parts) > 1 {
		operation = parts[1]
	}

	// 修复条件判断逻辑
	operationSuffix := ""
	if operation != "" {
		operationSuffix = "/" + operation
	}

	switch method {
	case "GET":
		return "查询" + module + operationSuffix
	case "POST":
		return "创建" + module + operationSuffix
	case "PUT":
		return "更新" + module + operationSuffix
	case "DELETE":
		return "删除" + module + operationSuffix
	default:
		return "操作" + module + operationSuffix
	}
}
